package org.geekbang.projects.cs.im.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.geekbang.projects.cs.im.packet.LoginRequestPacket;
import org.geekbang.projects.cs.im.packet.LoginResponsePacket;
import org.geekbang.projects.cs.im.util.LoginUtil;
import org.geekbang.projects.cs.im.util.Session;
import org.geekbang.projects.cs.im.util.SessionUtil;

/**
 * @description:
 * @author: Kaijun Chen
 * @date: 2023/3/15
 **/
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    private LoginRequestHandler() {}

    private static LoginRequestHandler instance = new LoginRequestHandler();

    public static LoginRequestHandler getInstance() {
        return instance;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestPacket loginRequestPacket) throws Exception {
        LoginResponsePacket responsePacket = login(channelHandlerContext, loginRequestPacket);

        channelHandlerContext.channel().writeAndFlush(responsePacket);
    }

    private LoginResponsePacket login(ChannelHandlerContext channelHandlerContext, LoginRequestPacket loginRequestPacket) {
        LoginResponsePacket responsePacket = new LoginResponsePacket();
        if (checkLogin(channelHandlerContext, loginRequestPacket)) {
            responsePacket.setCode("0000");
            responsePacket.setMsg("登录成功");
            LoginUtil.markAsLogin(channelHandlerContext.channel());
            SessionUtil.bindSession(new Session(loginRequestPacket.getUserId(), loginRequestPacket.getUserName()), channelHandlerContext.channel());
        } else {
            responsePacket.setCode("1001");
            responsePacket.setMsg("登录失败");
        }
        return responsePacket;
    }

    private boolean checkLogin(ChannelHandlerContext channelHandlerContext, LoginRequestPacket loginRequestPacket) {
        return !SessionUtil.hasLogin(channelHandlerContext.channel());
    }
}
